package com.news.dao.impl;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import com.news.dao.BaseDao;
import com.news.dao.NewsDao;
import com.news.entity.News;
import com.news.entity.User;

public class NewsDaoImpl extends BaseDao implements NewsDao {

	@Override
	public List<News> getAllNews() {
		String sql="SELECT * FROM `xinwen_table`";
		return getNews(sql);
	}

	@Override
	public List<News> getNewsByTid(Integer tid) {
		String sql="SELECT * FROM `xinwen_table` where tid ="+tid;
		return getNews(sql);
	}

	@Override
	public News getNewsById(Integer xwid) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public int addNews(News news) {
		// TODO Auto-generated method stub
		return 0;
	}
	
	/**
	 * 通用查询方法
	 */

	public List<News> getNews(String sql) {
		List<News> newslist = new ArrayList<>();
		Connection con=getCon();
		Statement stmt=null;
		ResultSet rs=null;
		
		try {
			System.out.println("创建执行对象");
			stmt=con.createStatement();
			System.out.println("获取结果集");
			rs=stmt.executeQuery(sql);
			while(rs.next()) {
				News news=new News();
				news.setXwid(rs.getInt("xwid")); //	 'xwid',
				news.setTitle(rs.getString("title"));					//  'title',
				news.setUid(rs.getInt("uid"));	//  'uid',
				news.setPublishtime(rs.getTimestamp("publishtime"));	// 'publishtime',
				news.setContent(rs.getString("content"));	// 'content',
				news.setClickcount(rs.getInt("clickcount"));	// 'clickcount',
				news.setTid(rs.getInt("tid"));	// 'tid'
				
				newslist.add(news);
			}			
		} catch (SQLException e) { 
			e.printStackTrace();
		}finally {
			closeAll(con, stmt, rs);
		}
		return newslist;
	}

	public static void main(String[] args) {
		NewsDao ndao=new NewsDaoImpl();
		List<News> newslist=ndao.getAllNews();
		newslist.forEach(System.out::println);
	}

}
